<template>
	<view>
		<view class='title'>请选择相应的地锁</view>
		<view class="container">
			<view v-for="(item,index) in list" :key="index" @click="handleSelect(item)">
				<view :class="['box', {'selected': selectedTd === item.channel}, {'disabled': shouldDisable(item)}]"
					@click="selectBox(index + 1)">
					<view class="box-item">
						<image class='box-img' :src="item.imgUrl" />
						<view>{{abc[item.channel - 1]}}枪地锁
							<text
								:style="{color: item.stauts == 0 ? '#19be6b' : (item.stauts == 1 ? '#19be6b' : '#dd524d')}">
								{{item.stauts == 0 ? '上升' : (item.stauts == 1 ? '下降' : '占用')}} </text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="btn">
			<u-button type="primary" shape="circle" :text="isParkingLockOrder ? '上升' : '下降'"
				@click='handleLowerPl'></u-button>
			<u-button style="margin-top: 20rpx;" type="primary" shape="circle"
				v-if='isParkingLockOrder && !isEndChargeOrder' text="去充电" @click='toChargePage'></u-button>
		</view>
		<!-- <view class="btn">
			<u-button type="primary" shape="circle" text="升地锁" @click='handleLower'></u-button>
		</view> -->
		<zmodal ref="zmodal"></zmodal>
		<u-modal title="" :show="show" :mask-close-able="true" :show-title="false">
			<view class="box-tips">
				<view class="title u-flex u-row-center z-type-cdz">
					{{ $z.$t("充电须知") }}
				</view>
				<view class="item1">
					{{ $z.$t("1、此车位为新能源汽车充电车位，在车辆充电期间将不收取占位费，只收取充电费用。")}}
				</view>
				<view class="item1">
					2、{{ $z.$t("请将车辆停到车位锁上方。") }}
				</view>
				<view class="item1">
					3、{{tipThree}}
				</view>
				<view class="item1">
					4、{{ $z.$t("为车辆充电时需要先插好充电枪再点击充电按钮。") }}
				</view>
				<view class="item1">
					5、{{ tipFive }}
				</view>
				<view class="item1">
					6、{{ tipSix}}
				</view>
				<view class="item1">
					7、{{ $z.$t("充电结束您将收到公众号充电结束提醒，请及时挪车，避免额外支付占位费。")}}
				</view>
				<view class="item1">
					8、{{ $z.$t("同一个用户同一时间段之内只能启动一笔地锁订单。")}}
				</view>
				<view class="item1">
					{{ $z.$t("温馨提示:若不充电或已完成充电，请手机上操作车位锁完全上升后离开，否则其它车辆进入后将会扣取您的占位费。")}}
				</view>
			</view>
			<template #confirmButton>
				<view style="padding: 0 20rpx">
					<u-button type="primary" @click="handleClose()">
						{{ $z.$t("我已知晓") }}
					</u-button>
				</view>
			</template>
		</u-modal>

	</view>
</template>

<script>
	import qs from "qs";
	export default {
		data() {
			return {
				ChargeCarSys: {},
				gtel: '',
				abc: ["A", "B"],
				selectedTd: null, // 假设 selectedTd 用于记录选中的索引
				isParkingLockOrder: false, //是否有地锁订单
				show: false,
				isUnpaidOrder: false, //是否有未支付的订单
				unfinishedOrder: {},
				anyOccupied: false, // 新增全局占用状态
				occupiedChannels: [],
				parkingLockOrderData: {},
				isEndChargeOrder: false, //是否有未结束的充电订单
				ChargeCar: [],
				isThrottling: false, // 节流标志位
				throttleDelay: 2000, // 节流时间，单位毫秒（例如 2 秒
				isModalShown: false, // 标志位，用于控制弹窗是否已经显示
				isNoOccupyTdObj: {},
				isNoOccupyUser: false,
				isAllUUserValid: false,
			}
		},
		asyncComputed: {
			// 获取通道的状态，并对通道进行禁用
			async list() {
				let ChargeCarSys = await this.$z.request("/ChargeCarSys", {
					gtel: this.gtel,
				});
				ChargeCarSys = ChargeCarSys[0];
				let gls = ChargeCarSys.gls || "0";
				// let abc = ["A", "B"];

				// 创建通道数组
				const channels = Array.from({
					length: gls
				}, (_, i) => i + 1);

				// 并行获取所有通道状态
				const statusRequests = channels.map(async (td) => {
					if (!this.$store.state.user.USearch.uUser) {
						await this.$store.dispatch("user/getuser");
					}
					let USearch = this.$store.state.user.USearch;
					try {
						//调用接口查看该设备是否有地锁订单，如果没有下降 如果有
						const res = await this.$z.request("/ChargeUserDs", {
							gtel: this.gtel,
							td: td,
						});
						// 判断是否存在未结束订单
						const isOccupied = res.some(item => item.b_end == 0);
						let data = res.find(item => item.b_end == 0);
						console.log('data', data);
						// isOccupied是 false 表示空闲
						// USearch.uUser = 'liliang'
						// console.log('USearch', data.uUser, USearch.uUser);
						if (data && data.uUser == USearch.uUser) {
							return {
								channel: td,
								stauts: isOccupied ? 0 : 1, // 0:占用 1:空闲
								imgUrl: `../../static/channel${td}.png`,
								uUser: isOccupied ? data.uUser : ''
							};
						} else {
							console.log(2222222222222, data && data.b_end != 0);
							return {
								channel: td,
								stauts: data && data.b_end == 0 ? 2 : 1, // 2:占用 1:空闲
								imgUrl: `../../static/channel${td}.png`,
								uUser: isOccupied ? data.uUser : ''
							};
						}
					} catch (error) {
						console.error(`获取通道${td}状态失败:`, error);
						return {
							channel: td,
							stauts: 1, // 默认设为空闲
							imgUrl: `../../static/channel${td}.png`,
							uUser: ''
						};
					}
				});

				const items = await Promise.all(statusRequests);
				console.log('items1', items);
				// 新增：全局占用状态检测
				// 新增：记录所有占用通道


				this.occupiedChannels = items.filter(item => item.stauts === 0).map(item => item.channel);
				return items;
			},
			tipThree() {
				let res = this.$z.$t("请在停入后的{1}分钟之内启动充电，否则将直接开始占位费计算。")
				res = res.replace(/\{1\}/g, 10);
				return res;
			},
			tipFive() {
				let res = this.$z.$t("免费停放时间=车辆充电时长+{1}分钟，超过{2}分钟则需支付占位费{3}元/{4}分钟。")
				res = res.replace(/\{1\}/g, this.ChargeCarSys.jebd);
				res = res.replace(/\{2\}/g, this.ChargeCarSys.jebd);
				res = res.replace(/\{3\}/g, this.ChargeCarSys.qbf / 100);
				res = res.replace(/\{4\}/g, this.ChargeCarSys.dfsj);
				return res;
			},
			tipSix() {
				let res = this.$z.$t("地锁在无遮挡物的情况下{1}秒后自动升起，也可以在无遮挡物的情况下手动点击相应按钮可立刻升起。")
				res = res.replace(/\{1\}/g, '120');
				return res;
			},
		},
		watch: {
			list: {
				immediate: true,
				handler(newVal) {
					// 添加对 list 是否为 null 或未定义的判断
					if (newVal && newVal.length > 0) {
						this.checkAndSelectChannel();
					}
				}
			}
		},
		async onLoad(query) {
			const params = query.gtel.split("_");
			this.gtel = params[0];
			this.td = params.length > 1 ? parseInt(params[1]) : 0; // 确保转换为数字类型
			console.log('设备通道码', this.gtel, this.td);
			// 调用地锁查询接口，查询用户的地锁订单状态
			await this.seachParkingLockOrder()
			// 查询用户是否有充电中的订单
			await this.searchUser()
			// 查询设备是否急停
			await this.searchDeviceStop()
			if (!this.$store.state.user.USearch.uUser) {
				await this.$store.dispatch("user/getuser");
			}
			let USearch = this.$store.state.user.USearch;
			// 是否有未占用的数据
			this.isNoOccupyTdObj = this.list.find(item => item.uUser == '')
			this.isNoOccupyUser = this.list.some(item => item.uUser == USearch.uUser)
			const isNoOccupyUserShow = this.list.find(item => item.uUser == USearch.uUser)
			this.isAllUUserValid = this.list.every(item => item.uUser);
			console.log('list', this.list, this.isAllUUserValid);
			if (this.isEndChargeOrder) {
				// 查询用户是否有未结束的充电订单 如果有跳转到充电页面
				uni.navigateTo({
					url: `/pages/ChargeUser/ChargeUser`,
				});
			} else if (this.isUnpaidOrder) {
				// 查询用户是否有已经结束的充电订单 但地锁订单未支付
				this.handleUnpaidOrderTips()
			} else if (this.ChargeCar.gcdl3 == 2) {
				// 查询设备是否有急停
				this.$refs.zmodal.init({
					title: '提示',
					content: `急停已被按下，请顺时针旋转急停按钮恢复使用`,
					confirm: () => {
						uni.reLaunch({
							url: "/pages/home1/home1"
						})
					}
				})
			} else if (this.isNoOccupyUser && this.td != this.parkingLockOrderData.td) {
				this.$refs.zmodal.init({
					title: '提示',
					content: `一个用户同一时间段只能充一笔地锁订单`,
					confirm: () => {}
				})
				this.selectedTd = null;
			} else if (this.isParkingLockOrder && this.parkingLockOrderData.td != this.td) {
				this.$refs.zmodal.init({
					title: '提示',
					content: `该设备已被占用，请重新选中通道码`,
					confirm: () => {}
				})
				this.selectedTd = null;
			} else if (this.isAllUUserValid && !isNoOccupyUserShow) {
				this.isAllUUserValid = true
				this.$refs.zmodal.init({
					title: '提示',
					content: `该设备暂无空闲枪，请选择其它充电桩`,
					confirm: () => {
						this.$z.sys()
					}
				})
				this.selectedTd = null;
			} else {
				this.selectedTd = this.td
				this.show = true
			}

			this.syncTimer = setInterval(async () => {
				this.seachParkingLockOrder()
				this.list = await this.$options.asyncComputed.list.call(this);
			}, 10000); // 每10秒同步一次
			// else if (this.isParkingLockOrder && !this.isEndChargeOrder) {
			// 	// 查询用户是否有未结束的占位订单
			// 	this.handleShowTips()
			// }
		},
		// 在页面销毁时清除
		onUnload() {
			clearInterval(this.syncTimer);
		},
		methods: {
			async checkAndSelectChannel() {
				// 等待列表数据加载完成
				await this.$nextTick();

				if (this.td > 0) {
					const targetIndex = this.td - 1;
					// if(this.parkingLockOrderData.td !=){}
					if (this.list[targetIndex]) {
						const channel = this.list[targetIndex];
						console.log('channel.stauts', channel.stauts);
						// channel.stauts == 0 ||
						if (channel.stauts == 2 && !this.isModalShown) {
							this.$refs.zmodal.init({
								title: this.$z.$t("提示"),
								content: this.$z.$t("该通道已被占用，无法选择"),
								showCancel: false
							});
							this.selectedTd = null; // 强制取消选中
							this.isModalShown = true; // 标记弹窗已显示
						} else {
							this.selectedTd = channel.channel;
						}
					}
				}
			},
			// 查询设备是否急停
			async searchDeviceStop() {
				let ChargeCarSys = await this.$z.request("/ChargeCarSys", {
					gtel: this.gtel,
				});
				this.ChargeCarSys = ChargeCarSys[0]

			},
			// 查询用户是否有充电中的订单
			async searchUser() {
				if (!this.$store.state.user.USearch.uUser) {
					await this.$store.dispatch("user/getuser");
				}
				let USearch = this.$store.state.user.USearch;
				let ChargeUser = await this.$z.request("/ChargeUser", {
					uUser: USearch.uUser,
				});
				this.isEndChargeOrder = ChargeUser.some(item => item.b_end == 0)

			},
			shouldDisable(item) {
				console.log('这是什么', item);

				// 如果当前是自动选择状态，并且用户手动点击了该通道，则不禁用
				if (this.td !== 0 && item.channel === this.selectedTd && this.isManualSelect) {
					return false;
				}

				// 原有逻辑保持不变...
				const currentUser = this.$store.state.user?.USearch?.uUser || '';
				switch (item.stauts) {
					case 0:
						return !(item.uUser === currentUser);
					case 2:
						return true;
					default:
						return this.occupiedChannels.length > 0;
				}

			},
			handleSelect(item) {
				this.isManualSelect = true;

				// 如果是通过td参数自动选择的，禁止手动操作
				console.log('item', item);
				if (!this.isParkingLockOrder) {
					return
				}
				// console.log('this.isParkingLockOrder11111111', this.isParkingLockOrder, this.parkingLockOrderData.td, this
				// 	.td);
				if (item.channel == 0 || item.channel == 2) {
					this.$u.toast(this.$z.$t("当前通道已被系统锁定"));
					// this.selectedTd = 0
					return;
				}

				// 原有逻辑保持不变...
				if (this.shouldDisable(item)) {
					console.log(`禁止操作通道${item.channel}`);
					return;
				}
				this.selectedTd = item.channel;
			},
			// 查询地锁订单
			async seachParkingLockOrder() {
				if (!this.$store.state.user.USearch.uUser) {
					await this.$store.dispatch("user/getuser");
				}
				let USearch = this.$store.state.user.USearch;
				let ChargeUserDs = await this.$z.request("/ChargeUserDs", {
					uUser: USearch.uUser,
				});
				this.isParkingLockOrder = ChargeUserDs.some(item => item.b_end == 0);
				this.parkingLockOrderData = ChargeUserDs.find(item => item.b_end == 0);
				console.log('this.parkingLockOrderData', this.parkingLockOrderData);
				this.unfinishedOrder = ChargeUserDs.find(item => item.b_zf == 0);
				this.isUnpaidOrder = ChargeUserDs.find(item => item.b_zf == 0 && item.b_end == 1)
				console.log('this.isUnpaidOrder', this.isUnpaidOrder);
				console.log('ChargeUserDs', ChargeUserDs);
			},
			// 未缴费的弹窗
			handleUnpaidOrderTips() {
				this.$refs.zmodal.init({
					content: this.$z.$t("系统检测到您当前存在未缴纳的占位订单，请支付后再使用。"),
					showcancel: false,
					showconfirm: true,
					title: this.$z.$t("温馨提示"),
					confirmText: this.$z.$t("打开占位订单"),
					confirm: () => {
						uni.reLaunch({
							url: `/pages/order/components/components/placeholderOrderInfo?ddh=${this.unfinishedOrder.ddh}&gtel=${this.gtel}_${this.td}`
						})
					},
					cancel: () => {}
				});
			},
			// 有占位订单弹窗
			handleShowTips() {
				this.$refs.zmodal.init({
					content: this.$z.$t("尊敬的用户，系统检测到您当前有占位订单。"),
					title: this.$z.$t("温馨提示"),
					showcancel: true,
					confirmText: this.$z.$t("去充电"),
					cancelText: this.$z.$t("取消"),
					confirm: () => {

					},
					cancel: () => {}
				});
			},
			toChargePage() {
				uni.navigateTo({
					url: `/pages/ChargeCarSys/ChargeCarSys?gtel=${this.gtel}_${this.parkingLockOrderData.td}&openChargeType=1`,
				});
			},
			selectBox(index) {
				if (this.anyOccupied) {
					this.$u.toast('当前存在进行中订单，请先处理');
					return;
				}
				this.selectedTd = index;

				console.log('this.selectedTd', this.selectedTd);
			},
			async handleLowerPl() {
				if (this.isThrottling) {
					this.$u.toast(this.$z.$t("操作过于频繁，请稍后再试"));
					return;
				}

				// 设置节流标志位
				this.isThrottling = true;

				try {
					if (this.selectedTd == null) {
						this.$u.toast(this.$z.$t("请选择地锁通道"));
						return;
					}

					// 获取选中通道的状态
					const selectedChannel = this.list.find(item =>
						item.channel === this.selectedTd
					);
					console.log('selectedChannel', selectedChannel);

					// 查询降地锁和升地锁是否为同一人
					if (!this.$store.state.user.USearch.uUser) {
						await this.$store.dispatch("user/getuser");
					}
					let USearch = this.$store.state.user.USearch;

					// if (selectedChannel.uUser != USearch.uUser && selectedChannel.uUser) {
					// 	this.$refs.zmodal.init({
					// 		content: this.$z.$t("系统检测到您降地锁和升地锁不是同一人，无法执行升地锁操作"),
					// 		showcancel: false,
					// 		showconfirm: true,
					// 		title: this.$z.$t("温馨提示"),
					// 		confirmText: this.$z.$t("我已知晓"),
					// 		confirm: () => {},
					// 		cancel: () => {}
					// 	});
					// 	return;
					// }

					// 状态1 是空闲 状态 0 是占用
					if (selectedChannel.stauts == 1) {
						const RoadOpen = await uni.$z.request("/RoadOpen", {
							gtel: this.gtel,
							td: this.selectedTd
						});
						if (RoadOpen[0].par == 'succeed') {
							this.zfokfn();
							// 更新占用通道列表
							this.occupiedChannels.push(this.selectedTd);
						} else {
							this.$u.toast(this.$z.$t("操作失败，请稍后重试"));
						}
					} else if (selectedChannel.stauts == 0) {
						this.$refs.zmodal.init({
							content: this.$z.$t("请确保您的车已离开车位且地锁上无遮挡物。"),
							title: this.$z.$t("温馨提示"),
							confirmText: this.$z.$t("确认"),
							cancelText: this.$z.$t("取消"),
							confirm: async () => {
								let ChargeDS = await this.$z.request("/ChargeDS", {
									gtel: this.gtel
								});
								let dqChargeDS = ChargeDS.find(e => {
									return e.td == this.selectedTd;
								});
								if (dqChargeDS) {
									await this.$z.request("/ChargeSetYKCadd", {
										gtel: dqChargeDS.gtelds,
										lx: 8,
										td: dqChargeDS.tdds,
										df: 0
									});
									this.$u.toast("升起地锁成功");
									// 更新占用通道列表
									this.occupiedChannels = this.occupiedChannels.filter(channel =>
										channel !==
										this.selectedTd);
								} else {
									this.$u.toast("升起地锁失败");
								}
								this.list = await this.$options.asyncComputed.list.call(this);
							},
							cancel: () => {}
						});
					}
				} catch (error) {
					console.error("handleLowerPl error:", error);
					this.$u.toast(this.$z.$t("操作失败，请稍后重试"));
				} finally {
					// 节流时间结束后重置标志位
					setTimeout(() => {
						this.isThrottling = false;
					}, this.throttleDelay);
				}
			},
			zfokfn() {
				let page = "";
				const zftext = '打开地锁'
				const reqdata = {
					gtel: this.gtel,
					td: this.selectedTd,
					btntext: '打开地锁',
					paramsUrl: '/ChargeAskDs'
				}
				console.log('this.reqdata', this.reqdata);
				page = `/pages/ChargeAsk/ChargeAsk?${qs.stringify(reqdata)}`;
				uni.redirectTo({
					url: page,
				});
			},
			// 关闭占位费弹窗
			handleClose() {
				this.show = false
			}
		}
	}
</script>

<style lang="scss">
	.title {
		padding-top: 48rpx;
		padding-left: 34rpx;
		font-weight: 600;
		font-size: 32rpx;
		color: #333333;
		line-height: 44rpx;
	}

	.box.auto-selected {
		border-color: #ff7900 !important;
		background: #fff4e6 !important;
	}

	.container {
		display: flex;
		justify-content: space-between;
		padding: 40rpx 82rpx 128rpx;

		.box {
			width: 272rpx;
			height: 240rpx;
			border-radius: 16rpx;
			background: #F6FAFF;
			text-align: center;
			padding: 56rpx 0;

			.box-img {
				margin-bottom: 24rpx;
				width: 124rpx;
				height: 64rpx;
			}
		}

		/* 在style部分添加状态样式 */
		.box.occupied {
			border: 2rpx solid #dd524d;
			background: #feeeed;
		}

		.box.free {
			border: 2rpx solid #19be6b;
			background: #f5fff9;
		}

		.box.selected {
			border: 2rpx solid #2093F5;
		}
	}

	.btn {
		padding: 0 64rpx;
	}

	.box-tips {
		.title {
			margin-bottom: 20rpx;
			color: #2093F5;
			font-weight: 500;
			padding-top: 0;
		}

		.item1 {
			padding: 0 0rpx 20rpx 0rpx;
			font-size: 24rpx;
			color: $uni-text-color-grey;
			line-height: 1.6;
		}
	}

	/* 优化禁用样式 */
	/* 保持原有禁用样式不变 */
	.box.disabled {
		opacity: 0.5;
		filter: grayscale(1);
		pointer-events: none;
	}

	.box.selected {
		box-shadow: 0 8rpx 24rpx rgba(32, 147, 245, 0.2);
		transform: translateY(-8rpx);
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	}

	.box {
		/* 基础样式 */
		transition: all 0.3s ease;

		/* 禁用状态 */
		&.disabled {
			opacity: 0.6;
			filter: grayscale(0.8);
			cursor: not-allowed;
			box-shadow: none;

			/* 占用状态特殊样式 */
			&[data-status="occupied"] {
				border-color: #dd524d;
				background: linear-gradient(45deg, #feeeed, #fff5f5);
			}
		}

		/* 选中状态 */
		&.selected {
			border: 2rpx solid #2093F5;
			box-shadow: 0 8rpx 24rpx rgba(32, 147, 245, 0.2);
		}
	}
</style>